<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="~{layout/default}">
<head>
    <title th:text="${template != null ? '编辑模板' : '创建模板'} + ' - 废物回收管理系统'"></title>
    <style>
        .preview-box {
            border: 1px solid #dee2e6;
            border-radius: 0.25rem;
            padding: 1rem;
            margin-top: 0.5rem;
            background-color: #f8f9fa;
        }
        .variable-item {
            display: inline-block;
            margin: 0.25rem;
            padding: 0.25rem 0.5rem;
            background-color: #e9ecef;
            border-radius: 0.25rem;
            cursor: pointer;
        }
        .CodeMirror {
            height: 200px;
            border: 1px solid #dee2e6;
            border-radius: 0.25rem;
        }
    </style>
</head>
<body>
    <div layout:fragment="content">
        <div class="container-fluid">
            <!-- 标题和返回按钮 -->
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h4 th:text="${template != null ? '编辑模板' : '创建模板'}"></h4>
                <a href="/template/list" class="btn btn-outline-secondary">
                    <i class="fas fa-arrow-left"></i> 返回列表
                </a>
            </div>

            <!-- 编辑表单 -->
            <div class="card">
                <div class="card-body">
                    <form id="templateForm" class="row g-3">
                        <input type="hidden" name="id" th:value="${template?.id}">
                        
                        <div class="col-md-6">
                            <label class="form-label">模板代码 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="code" th:value="${template?.code}"
                                   required pattern="[A-Z_]+" maxlength="50"
                                   placeholder="请输入模板代码（大写字母和下划线）">
                            <div class="form-text">例如：ORDER_CREATED、SYSTEM_NOTICE</div>
                        </div>
                        
                        <div class="col-md-6">
                            <label class="form-label">模板名称 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="name" th:value="${template?.name}"
                                   required maxlength="100" placeholder="请输入模板名称">
                        </div>
                        
                        <div class="col-md-6">
                            <label class="form-label">消息类型 <span class="text-danger">*</span></label>
                            <select class="form-select" name="type" required>
                                <option value="">请选择消息类型</option>
                                <option value="ORDER" th:selected="${template?.type == 'ORDER'}">订单通知</option>
                                <option value="SYSTEM" th:selected="${template?.type == 'SYSTEM'}">系统通知</option>
                            </select>
                        </div>
                        
                        <div class="col-md-6">
                            <label class="form-label">状态</label>
                            <select class="form-select" name="status">
                                <option value="1" th:selected="${template?.status == 1}">启用</option>
                                <option value="0" th:selected="${template?.status == 0}">禁用</option>
                            </select>
                        </div>
                        
                        <div class="col-12">
                            <label class="form-label">变量定义（JSON格式）</label>
                            <textarea class="form-control" name="variables" id="variables" rows="3"
                                    th:text="${template?.variables}"></textarea>
                            <div class="form-text">例如：{"orderNo": "订单号", "userName": "用户名称"}</div>
                            <div id="variableList" class="mt-2"></div>
                        </div>
                        
                        <div class="col-md-6">
                            <label class="form-label">消息标题模板 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="title" th:value="${template?.title}"
                                   required maxlength="200" placeholder="请输入消息标题模板">
                            <div id="titlePreview" class="preview-box"></div>
                        </div>
                        
                        <div class="col-md-6">
                            <label class="form-label">消息内容模板 <span class="text-danger">*</span></label>
                            <textarea class="form-control" name="content" rows="3" required
                                    maxlength="1000" placeholder="请输入消息内容模板"
                                    th:text="${template?.content}"></textarea>
                            <div id="contentPreview" class="preview-box"></div>
                        </div>
                        
                        <div class="col-12">
                            <label class="form-label">备注</label>
                            <textarea class="form-control" name="remark" rows="2" maxlength="500"
                                    placeholder="请输入备注信息" th:text="${template?.remark}"></textarea>
                        </div>
                        
                        <div class="col-12">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save"></i> 保存
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <th:block layout:fragment="scripts">
        <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/codemirror.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/mode/javascript/javascript.min.js"></script>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/codemirror.min.css">
        
        <script>
            let editor;
            
            document.addEventListener('DOMContentLoaded', function() {
                // 初始化JSON编辑器
                editor = CodeMirror.fromTextArea(document.getElementById('variables'), {
                    mode: 'javascript',
                    lineNumbers: true,
                    matchBrackets: true
                });
                
                // 监听变量变化
                editor.on('change', function() {
                    updateVariableList();
                });
                
                // 初始化变量列表
                updateVariableList();
                
                // 监听标题和内容变化
                document.querySelector('[name="title"]').addEventListener('input', updatePreviews);
                document.querySelector('[name="content"]').addEventListener('input', updatePreviews);
                
                // 表单提交
                document.getElementById('templateForm').addEventListener('submit', function(e) {
                    e.preventDefault();
                    saveTemplate();
                });
            });
            
            // 更新变量列表
            function updateVariableList() {
                try {
                    const variables = JSON.parse(editor.getValue() || '{}');
                    const list = document.getElementById('variableList');
                    list.innerHTML = '';
                    
                    Object.entries(variables).forEach(([key, desc]) => {
                        const item = document.createElement('div');
                        item.className = 'variable-item';
                        item.textContent = `{{${key}}}`;
                        item.title = desc;
                        item.onclick = () => insertVariable(key);
                        list.appendChild(item);
                    });
                } catch (e) {
                    document.getElementById('variableList').innerHTML = 
                        '<div class="text-danger">JSON格式错误</div>';
                }
            }
            
            // 插入变量到当前焦点
            function insertVariable(key) {
                const activeElement = document.activeElement;
                if (activeElement.tagName === 'INPUT' || activeElement.tagName === 'TEXTAREA') {
                    const start = activeElement.selectionStart;
                    const end = activeElement.selectionEnd;
                    const value = activeElement.value;
                    const variable = `{{${key}}}`;
                    
                    activeElement.value = value.substring(0, start) + variable + value.substring(end);
                    activeElement.selectionStart = activeElement.selectionEnd = start + variable.length;
                    activeElement.focus();
                    
                    updatePreviews();
                }
            }
            
            // 更新预览
            function updatePreviews() {
                try {
                    const variables = JSON.parse(editor.getValue() || '{}');
                    const testData = {};
                    Object.keys(variables).forEach(key => {
                        testData[key] = `[${variables[key]}]`;
                    });
                    
                    const title = document.querySelector('[name="title"]').value;
                    const content = document.querySelector('[name="content"]').value;
                    
                    document.getElementById('titlePreview').textContent = replaceVariables(title, testData);
                    document.getElementById('contentPreview').textContent = replaceVariables(content, testData);
                } catch (e) {
                    console.error('预览更新失败:', e);
                }
            }
            
            // 替换变量
            function replaceVariables(template, variables) {
                return template.replace(/\{\{(\w+)\}\}/g, (match, key) => 
                    variables[key] !== undefined ? variables[key] : match
                );
            }
            
            // 保存模板
            function saveTemplate() {
                const form = document.getElementById('templateForm');
                const formData = new FormData(form);
                const template = Object.fromEntries(formData.entries());
                
                // 更新变量值
                template.variables = editor.getValue();
                
                const isEdit = template.id;
                const url = isEdit ? '/template/update' : '/template/create';
                const method = isEdit ? 'PUT' : 'POST';
                
                fetch(url, {
                    method: method,
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(template)
                }).then(response => {
                    if (!response.ok) {
                        throw new Error('保存失败');
                    }
                    showToast('success', '保存成功');
                    setTimeout(() => {
                        window.location.href = '/template/list';
                    }, 1000);
                }).catch(error => {
                    showToast('error', error.message);
                });
            }
        </script>
    </th:block>
</body>
</html> 